#!/usr/bin/python
# Import the CGI module
# -*- coding: UTF-8 -*-
import xmlrpclib
import cgi
import urllib
import pickle
import time

##http://201.231.210.250:32678/
class printer:
  def __init__(self,serverurl="http://localhost:32678"):
    self.temp = xmlrpclib.ServerProxy(serverurl)
    self.server = self.temp.feedreader
  def assignCategory(self, pickled, categories):
    ids={}
    inverseids={}
    existingtags=self.server.gettags()
    news=pickle.loads(urllib.unquote(pickled))
    oldtags=news["Tags"]
    for i in existingtags:
      ids[i["Name"]]=int(i["TagID"])
      #inverseids[i["TagID"]]=i["Name"]
    for i in categories.replace(" ,",",").replace(", ",",").split(","):
      if not ids.has_key(i):
        self.server.addtag(i)
    ##so far i added the tags that are new, now i need to get the existing categories again just to get the new cat number
    existingtags=self.server.gettags()
    for i in existingtags:
      ids[i["Name"]]=int(i["TagID"])
      inverseids[i["TagID"]]=i["Name"]
    newtags=[]
    for i in categories.replace(" ,",",").replace(", ",",").split(","):
      newtags.append(int(ids[i]))
    addedtags=[]
    deletedtags=[]
    for i in newtags:
      if i not in oldtags:
        addedtags.append(i)
    for i in oldtags:
      if i not in newtags:
        deletedtags.append(i) 
      
    retval1=self.server.assigntags(int(news["FeedID"]),int(news["NewsID"]),addedtags)
    retval2=self.server.removetags(int(news["FeedID"]),int(news["NewsID"]),deletedtags) 
    return (retval1==0 and retval2==0)
  def getCategories(self):
    retval = []
    t=self.server.gettags()
    for i in t:
      retval.append(i["Name"])
    return ','.join(retval)
  def getCatStruct(self):
    retval={}
    t=self.server.gettags()
    for i in t:
      retval[i["TagID"]]=i["Name"]     
    return retval
  def getinvCatStruct(self):
    retval={}
    t=self.server.gettags()
    for i in t:
      retval[i["Name"]]=int(i["TagID"])     
    return retval
  def getFeeds(self,page=0, count=10):
    news = self.server.getfeeds(page,count)
    print '<table border="0" cellpadding="1" cellspacing="1" width="100%">'
    print '<tbody><tr class="title_box">'
    print '<td colspan="3">Feed name</td>'
    print '<td colspan="3"><td>'
    print "</tr>"
    if page > len(news):
      st=len(news)
    else:
      st=page
    if page + count > len(news):
      stp=len(news)
    else:
      stp=count+page
    #print st
    #print stp
    for i in range(st,stp):
        print '<tr class="datalist" bgcolor="#080808">'
        print '<td><font color="#606060"><a href=\"feeds.py?' + urllib.urlencode({"pickled":pickle.dumps(news[i])}) + "\">" + news[i]["Name"] + "</a></td>"
        print "</tr>"
    print "</tbody></table>"
    return news
  def getFeedByNumber(self, pickled):
    feed = pickle.loads(pickled)    
    print '<table border="0">'
    print "<tr>"
    print "<td><b>Title</b></td>"
    print "</tr>"
    print "<tr>"
    print "<td><a href=\"" + feed["Url"] + "\">" + feed["Name"] + "</a></td>"
    print "</tr>"
    print "<tr>"
    print "<td><b>Date</b></td>"
    print "</tr>"
    print "<tr>"
    print "<td>" + time.ctime(feed["DateTime"]) + "</td>"
    print "</tr>"  
    print "</table>"
  def getNews(self, page=0, count=10):
    return self.server.getnews(page, count)
  def printNews(self,news):
    #loc = locale.getdefaultlocale()
    #print loc
    print '<table border="0" cellpadding="1" cellspacing="1" width="100%">'
    print '<tbody><tr class="title_box">'
    print ' <td colspan="3"> News</td>'
    print ' <td colspan="3"> Tags</td>'
    print '</tr>'
    for i in range(len(news)):
        print '<tr class="datalist" bgcolor="#080808">'
        news[i]["Description"]=news[i]["Description"].encode("latin-1","ignore")
        news[i]["Author"]=news[i]["Author"].encode("latin-1","ignore")
        news[i]["Title"]=news[i]["Title"].encode("latin-1","ignore")
        s=pickle.dumps(news[i])
        struct = {"pickled":s}
        availtags=self.getCatStruct()
        newscat=[]
        for j in news[i]["Tags"]:
          newscat.append(availtags[j])
        print '<td valign="middle"><font color="#606060"><a href="news.py?' + urllib.urlencode(struct) + "\">" + news[i]["Title"] + "</a></td>"
        print '<td valign="middle">' + ",".join(newscat) + "</td>"
        print "</tr>"
    print '</tbody></table>'
  def getNewsByNumber(self, news,paramcats="",empty=False):
    print "<table border=\"0\">"
    print "<tr>"
    print "<td><b>Title</b></td>"
    print "</tr>"
    print "<tr>"
    print "<td>" + news["Title"] + "</td>"
    print "</tr>"
    print "<tr>"
    print "<td><b>Date</b></td>"
    print "</tr>"
    print "<tr>"
    print "<td>" +  time.ctime(news["DateTime"]) + "</td>"
    print "</tr>"
    print "<tr>"
    print "<td><b>Descripcion</b></td>"
    print "</tr>"
    print "<tr>"
    print "<td>" + news["Description"].replace('\n','<br>') + "</td>"
    print "</tr>"
    print "<td><b>Tags</b></td>"
    print "</tr>"
    print "<tr>"
    #if empty == True:
    #  print "this was empty!!!!! <br>"
    if not empty:
      availtags=self.getCatStruct()
      newscat=[]
      for i in news["Tags"]:
        newscat.append(availtags[i])
      if paramcats=="":
        print "<td>" + ",".join(newscat) + "</td>"
      else:
        print "<td>" + paramcats + "</td>"
    else:
        print "<td>" + "</td>"
    print "</tr>" 
    print "</table>"
    return news
  def delFeed(self, id):
    return self.server.delfeed(id)
  def addFeed(self, id):
    return self.server.addfeed(id,id)
  def Search(self,feeds,intag, outtag,dateinit,dateend):
    return self.server.search(feeds,intag,outtag,dateinit,dateend)
    
if __name__ == "__main__":
  print "Content-Type: text/html\n\n"
  print "<html><head>"
  form = cgi.FieldStorage()
  if(form.has_key("id")):
    p = printer()
    p.getFeedByNumber(form["id"].value)
    print "\t\t<FORM METHOD = post ACTION = \"main.py\">\n"
    print "\t<INPUT TYPE = hidden NAME = \"delete\" VALUE = \"" + form["id"].value +"\">\n"
    print "\t<INPUT TYPE = submit VALUE = \"Delete\">\n"
    print "</body></html>"
